<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column align="center" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role-name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editUserHandle(scope.row)"
              plain
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUser(scope.row.id)"
              plain
            ></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                plain
                @click="showRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的弹窗 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="closeaddForm">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editFromClose">
      <el-form ref="editFromRef" :model="editFrom" :rules="editFromRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFromSave">修 改</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%">
      <div>
        <p>当前用户： {{roleInfo.username}}</p>
        <br />
        <p>当前角色： {{roleInfo.role_name}}</p>
        <br />
        <p>
          分配角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesLst"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 自定义邮箱规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }

    // 自定义手机规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (regMobile.test(value)) {
        cb()
      }
      cb(new Error('请输入正确的手机号'))
    }
    return {
      // 获取用户列表参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [], // 用户列表数据
      total: 0, // 用户总条数
      addDialogVisible: false,
      // 添加用户的数据对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加数据校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '请输入正确的密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 控制编辑弹窗的显示隐藏
      editDialogVisible: false,

      // 编辑用户数据对象
      editFrom: {},
      // 编辑数据校验规则
      editFromRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色弹窗的显示隐藏
      setRoleDialogVisible: false,
      // 获取的角色列表
      rolesLst: [],
      roleInfo: [],
      selectRoleId: ''
    }
  },
  created() {
    // 调用获取用户列表数据的方法
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userlist = res.data.users
      this.total = res.data.total
    },

    // pagesize 改变时 触发
    handleSizeChange(pagesize) {
      console.log(pagesize)
      this.queryInfo.pagesize = pagesize
      this.getUserList()
    },

    // 页面发生改变时触发
    handleCurrentChange(currentPage) {
      console.log(currentPage)
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },

    // 状态改变
    async stateChange(userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(`/users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 关闭添加表单重置
    closeaddForm() {
      this.$refs.addFormRef.resetFields()
    },

    // 添加用户
    addUser() {
      // 对表单进行校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发送请求
        const { data: res } = await this.$http.post('/users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 将弹窗关闭
        this.addDialogVisible = false
        // 重新刷新
        this.getUserList()
      })
    },

    // 编辑用户功能
    editUserHandle(userInfo) {
      this.editFrom = userInfo
      this.editDialogVisible = true
    },

    // 重置编辑弹框
    editFromClose() {
      this.$refs.editFromRef.resetFields()
    },

    // 编辑完保存
    editFromSave() {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`/users/${this.editFrom.id}`, {
          email: this.editFrom.email,
          mobile: this.editFrom.mobile
        })

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 刷新页面
        this.getUserList()
        // 成功后的提示
        this.$message.success(res.meta.msg)
        // 关闭弹窗
        this.editDialogVisible = false
      })
    },

    // 删除用户
    async removeUser(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果 confirmResult 返回值是 confirm 代码同意删除
      // 如果 confirmResult 返回值是 concel 代码取消删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了删除')
      }

      // 执行删除操作
      const { data: res } = await this.$http.delete(`/users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },

    // 展示弹窗并获得角色数据
    async showRoles(roleInfo) {
      this.roleInfo = roleInfo
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesLst = res.data
      this.setRoleDialogVisible = true
    },

    //
    async setRole() {
      if (!this.selectRoleId) return this.$message.error('请选择角色')
      const { data: res } = await this.$http.put(`/users/${this.roleInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.stauts !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
